package com.kayang.webapi.tool;

import com.kayang.common.db.DatabaseFactory;
import com.kayang.nadapt.delegate.DataEventArgs3;
import com.kayang.nadapt.util.LogHelper;

import java.util.Collection;

public final class DBDebug {

    private static boolean _hasErrOnce;

    public static void init(String dbdebug) {
        //数据库执行语句跟踪
        String config = dbdebug;
        if (config.equals("true") || config.equals("1") ) {
            DatabaseFactory.ExecSql.addListener(DBDebug::databaseFactoryExecSql);
        }
    }

    //跟踪记录数据库执行的sql。需配置dbdebug=true
    private static void databaseFactoryExecSql(Object sender, DataEventArgs3<String, Long, Collection<Object>> e) {
        try {
            String dbMsg = String.format("PARAM = %1$s, TIME = %2$s, SQL = %3$s;",  e.getData3() == null ? "[]" : e.getData3().toString(), e.getData2() + "ms", e.getData1());
            LogHelper.logDB(dbMsg);
        } catch (RuntimeException ex) {
            if (!_hasErrOnce) {
                LogHelper.error(ex); //只记录一次，避免爆舱
            }
            _hasErrOnce = true;
        }
    }

}
